package com.golang.codegen.service.impl;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

import org.springframework.stereotype.Service;

import com.golang.codegen.entity.GenConfig;
import com.golang.codegen.mapper.SysGeneratorMapper;
import com.golang.codegen.service.SysGeneratorService;
import com.golang.codegen.util.GenUtils;
import com.golang.codegen.util.Query;

import cn.hutool.core.io.IoUtil;
import lombok.AllArgsConstructor;

/**
 * 代码生成器
 *
 * @author lzdn
 * @date 2018-07-30
 */
@Service
@AllArgsConstructor
public class SysGeneratorServiceImpl implements SysGeneratorService {
	private final SysGeneratorMapper sysGeneratorMapper;

	/**
	 * 分页查询表
	 *
	 * @param query
	 *            查询条件
	 * @return
	 */
	@Override
	public List<Map<String, Object>> queryPage(Query query) {
		Object tableName = query.getCondition().get("tableName");
		return sysGeneratorMapper.queryList(query, tableName);
	}

	/**
	 * 生成代码
	 *
	 * @param genConfig
	 *            生成配置
	 * @return
	 */
	@Override
	public byte[] generatorCode(GenConfig genConfig) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		for (String tableName : genConfig.getTableNames()) {
			// 查询表信息
			Map<String, String> table = queryTable(tableName);
			// 查询列信息
			List<Map<String, String>> columns = queryColumns(tableName);
			// 生成代码
			try {
				GenUtils.generatorCode(genConfig, table, columns, zip);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		IoUtil.close(zip);
		return outputStream.toByteArray();
	}

	private Map<String, String> queryTable(String tableName) {
		return sysGeneratorMapper.queryTable(tableName);
	}

	private List<Map<String, String>> queryColumns(String tableName) {
		return sysGeneratorMapper.queryColumns(tableName);
	}
}
